<!-- src/views/Register.vue -->
<template>
  <section class="py-16 bg-neutral min-h-screen flex items-center justify-center">
    <div class="w-full max-w-md bg-white rounded-xl shadow-lg p-8">
      <div class="text-center mb-8">
        <div class="w-16 h-16 rounded-lg bg-primary flex items-center justify-center mx-auto mb-4">
          <i class="fa fa-user-plus text-white text-2xl"></i>
        </div>
        <h2 class="text-2xl font-bold">创建账号</h2>
        <p class="text-gray-500 mt-2">注册后即可使用所有功能，开始你的漫画创作之旅</p>
      </div>
      
      <form @submit.prevent="handleRegister">
        <div class="mb-4">
          <label class="block text-sm font-medium mb-2" for="username">用户名</label>
          <input 
            type="text" 
            id="username" 
            v-model="username"
            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
            placeholder="请设置用户名"
            required
          >
        </div>
        

        
        <div class="mb-4">
          <label class="block text-sm font-medium mb-2" for="register-password">密码</label>
          <input 
            type="password" 
            id="register-password" 
            v-model="password"
            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
            placeholder="请设置密码（必须包含字母、数字和特殊字符，至少8位）"
            required
            minlength="8"
          >
        </div>
        
        <div class="mb-6">
          <label class="block text-sm font-medium mb-2" for="confirm-password">确认密码</label>
          <input 
            type="password" 
            id="confirm-password" 
            v-model="confirmPassword"
            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
            placeholder="请再次输入密码"
            required
            minlength="8"
          >
          <p v-if="password !== confirmPassword && confirmPassword" class="text-red-500 text-xs mt-1">
            两次输入的密码不一致
          </p>
        </div>
        
        <div class="flex items-center mb-6">
          <input 
            type="checkbox" 
            id="agree-terms" 
            v-model="agreeTerms"
            class="w-4 h-4 text-primary focus:ring-primary/50 border-gray-300 rounded"
            required
          >
          <label for="agree-terms" class="ml-2 text-sm text-gray-600">
            我已阅读并同意<a href="#" class="text-primary hover:underline">服务条款</a>和<a href="#" class="text-primary hover:underline">隐私政策</a>
          </label>
        </div>
        
        <button 
          type="submit"
          class="w-full py-3 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-colors shadow-md hover:shadow-lg"
          :disabled="password !== confirmPassword"
        >
          注册账号
        </button>
      </form>
      
      <div class="mt-6 text-center">
        <p class="text-gray-500 text-sm">
          已有账号？
          <router-link to="/login" class="text-primary font-medium hover:underline">立即登录</router-link>
        </p>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api, { apiRequest, DEBUG_MODE, API_BASE_URL } from '../utils/api'

// API基础URL从api.js导入，确保与登录功能配置一致

const username = ref('')

const password = ref('')
const confirmPassword = ref('')
const agreeTerms = ref(false)
const router = useRouter()

const handleRegister = async () => {
    // 使用更简单的密码校验方法
    
    // 检查长度
    if (password.value.length < 8) {
      alert('密码长度必须不少于8位！');
      return;
    }
    
    // 检查是否包含字母
    if (!/[A-Za-z]/.test(password.value)) {
      alert('密码必须包含字母！');
      return;
    }
    
    // 检查是否包含数字
    if (!/\d/.test(password.value)) {
      alert('密码必须包含数字！');
      return;
    }
    
    // 检查是否包含特殊字符
    if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~`]/.test(password.value)) {
      alert('密码必须包含特殊字符！');
      return;
    }
    
    // 所有校验通过，继续处理
  
  if (password.value !== confirmPassword.value) {
    alert('两次输入的密码不一致！')
    return
  }
  
  if (!agreeTerms.value) {
    alert('请阅读并同意服务条款和隐私政策！')
    return
  }
  
  try {
    // 准备注册数据
    const registerData = {
      username: username.value,
      password: password.value,
      confirm_password: confirmPassword.value
    }
    
    // 发送注册请求
    const response = await api.post('/user/register', registerData)
    
    // 解析响应数据
    const data = response
    
    console.log('注册成功:', data)
    
    // 检查是否是成功响应且有用户信息
    if (data.code === 0 && data.data) {
      // 保存用户信息到localStorage，实现自动登录效果
      localStorage.setItem('userInfo', JSON.stringify(data.data))
      alert('注册成功，欢迎！')
      // 检查是否有待处理的漫画生成请求
      const hasPendingSelections = localStorage.getItem('pendingComicSelections')
      // 跳转到首页，让HomeSection组件恢复用户的选择
      router.push('/')
    } else {
      // 否则跳转到登录页
      alert('注册成功，请登录！')
      router.push('/login')
    }
  } catch (error) {
    console.error('注册失败:', error)
    alert(`注册失败: ${error.message}`)
  }
}
</script>